package com.winz.cultureapp.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.core.content.FileProvider;
import androidx.core.content.PermissionChecker;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.winz.cultureapp.R;
import com.winz.cultureapp.utils.Logger;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 获取图像
 */
@SuppressLint("InflateParams")
public class GetPictureFragment extends DialogFragment {
	// 注册（1:1的裁剪）
	public static final int TYPE_REGIST = 22;

	private int outputX = 80;
	private int outputY = 80;
	private static final int CHOOSE_BIG_PICTURE = 101;// 裁剪
	private static final int REQUEST_PERMISSION_CODE = 267;
	private static final int TAKE_PHOTO = 189;
	private static final int CHOOSE_PHOTO = 385;

	private boolean isNeed = true; // 默认对图片进行裁剪

	private final String TAG = getClass().getSimpleName();

	private static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
	private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;

	private static final String FILE_PROVIDER_AUTHORITY = "com.winz.cultureapp.fileprovider";
	private Uri mImageUri, mImageUriFromFile, mCropImageUri,mCropImageUriFromFile;
	private File imageFile,cropImageFile;



	public GetPictureFragment() {

	}

	/**
	 * 单例模式
	 * @param type  是否按比例剪切图片
	 * @param isTake 是否是拍照
	 */
	public static GetPictureFragment newInstance(int type, boolean isTake) {
		GetPictureFragment fragment = new GetPictureFragment();
		Bundle b = new Bundle();
		b.putInt("type", type);
		b.putBoolean("isTake", isTake);
		fragment.setArguments(b);
		return fragment;
	}

	public static GetPictureFragment newInstance(int type, int outputX, int outputY, boolean isTake) {
		GetPictureFragment fragment = new GetPictureFragment();
		Bundle b = new Bundle();
		b.putInt("type", type);
		b.putInt("outputX", outputX);
		b.putInt("outputY", outputY);
		b.putBoolean("isTake", isTake);
		fragment.setArguments(b);
		return fragment;
	}


	/**
	 * 获取当前的类型
	 *
	 * @return
	 */
	private int getPictureType() {
		return getArguments().getInt("type");
	}

	/**
	 * 获取是否是拍照
	 *
	 * @return
	 */
	private boolean isTake() {
		return getArguments().getBoolean("isTake");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		outputX = getArguments().getInt("outputX");
		outputY = getArguments().getInt("outputY");

		setCancelable(true);// 表示当前的弹出框可以用返回键返回
		setStyle(STYLE_NO_TITLE, 0);// 设置弹出框没有标题(主题默认(可以用自定主题))

		/*申请读取存储的权限*/
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			Logger.i(TAG, "onActivityResult: ImageUriFromAlbum: " + getContext().checkSelfPermission(PERMISSION_WRITE_STORAGE));
			if (getContext().checkSelfPermission(PERMISSION_CAMERA) != PackageManager.PERMISSION_GRANTED) {
				requestPermissions(new String[]{PERMISSION_CAMERA,PERMISSION_WRITE_STORAGE}, REQUEST_PERMISSION_CODE);
			}
		}

		if (isTake()) { // 打开相机
			try {
				startCamera();
			}catch (Exception e) {
				dismiss();
			}
		} else { //打开相册
			getFromPictureHome();
		}

		// 剪辑之后的图片的缓存路径
		cropImageFile = createImageFile("crop_");
		mCropImageUriFromFile = Uri.fromFile(cropImageFile);

	}




	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View layout = inflater.inflate(R.layout.fragment_get_picture, null);
		return layout;
	}

	/**
	 * 打开相机
	 */
	private void startCamera() {
		Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
		if (takePhotoIntent.resolveActivity(getContext().getPackageManager()) != null) {//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
			imageFile = createImageFile("capture_");//创建用来保存照片的文件
			mImageUriFromFile = Uri.fromFile(imageFile);
			Log.i(TAG, "takePhoto: uriFromFile " + mImageUriFromFile);
			if (imageFile != null) {
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
					/*7.0以上要通过FileProvider将File转化为Uri*/
					mImageUri = FileProvider.getUriForFile(getContext(), FILE_PROVIDER_AUTHORITY, imageFile);
				} else {
					/*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
					mImageUri = Uri.fromFile(imageFile);
				}
				takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
				startActivityForResult(takePhotoIntent, TAKE_PHOTO);//打开相机
			}
		}
	}

	/**
	 * 打开相册
	 */
	private void getFromPictureHome() {
		Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
		openAlbumIntent.setType("image/*");
		startActivityForResult(openAlbumIntent, CHOOSE_PHOTO);//打开相册
	}

	/**
	 * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
	 *
	 * @return 创建的图片文件
	 */
	private File createImageFile(String type) {
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = type + timeStamp + "_";
		File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		File imageFile = null;
		try {
			imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return imageFile;
	}

	/*相机或者相册返回来的数据*/
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 调用系统的Activity后返回的结果码如果是Activity.RESULT_OK。否则表示没有选择图片就点返回键
		if (resultCode == Activity.RESULT_OK) {

			switch (requestCode) {
				case TAKE_PHOTO:
					galleryAddPic(mImageUriFromFile);
					if (isNeed){
						// 将拍照之后的图像进行裁剪，这里启动裁剪的Activity
						Intent intent = new Intent("com.android.camera.action.CROP");
						intent.putExtra("crop", "true");
						// aspectX aspectY 是宽高的比例
						intent.putExtra("aspectX", outputX);
						intent.putExtra("aspectY", outputY);
						// outputX outputY 是裁剪图片宽高
						intent.putExtra("outputX", outputX);
						intent.putExtra("outputY", outputY);

						intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
						intent.putExtra("return-data", false);
//						intent.putExtra("scale ", true);  //是否保留比例

						intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
						intent.setDataAndType(mImageUri, "image/*");  //设置数据源,必须是由FileProvider创建的ContentUri

						intent.putExtra(MediaStore.EXTRA_OUTPUT, mCropImageUriFromFile); //设置输出  不需要ContentUri,否则失败

						// 拍照完成后。调用了自己的Result的方法。到requestCode==CHOOSE_BIG_PICTURE
						startActivityForResult(intent, CHOOSE_BIG_PICTURE);
					} else {
						if (mImageUriFromFile != null) {
							if (null != onGetPictureListener) {
								onGetPictureListener.onComplete(mImageUriFromFile.getPath());
							}
						}
					}

					break;
				case CHOOSE_BIG_PICTURE:// 拍照完成到这里调用
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
						/*7.0以上要通过FileProvider将File转化为Uri*/
						mCropImageUri = FileProvider.getUriForFile(getContext(), FILE_PROVIDER_AUTHORITY, cropImageFile);
					} else {
						/*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
						mCropImageUri = Uri.fromFile(cropImageFile);
					}
					galleryAddPic(mCropImageUriFromFile);
					if (mCropImageUriFromFile != null) {
						if (null != onGetPictureListener) {
							onGetPictureListener.onComplete(mCropImageUriFromFile.getPath());
						}
					}
					/**
					 * 在该活动获得系统Activity返回的结果。处理完再返回结果回到注册界面的时候记得把当前自己的弹出框关闭掉。
					 * 但是注意的是，必须调用玩回调返回结果后再调用该方法关闭自己。否则自己
					 */
					GetPictureFragment.this.dismiss();// 在该活动获得系统Activity返回的结果。处理玩再返回结果回到注册界面的时候记得把当前自己的弹出框关闭掉。

					break;
				case CHOOSE_PHOTO:
					if (data == null) {//如果没有选取照片，则直接返回
						return;
					}

					if (isNeed){
						cropPhoto(data.getData());
					}else {
						Logger.i(TAG, "onActivityResult: ImageUriFromAlbum: " + data.getData());
						if (null != onGetPictureListener) {
							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
								//4.4之后图片解析
								onGetPictureListener.onComplete(handleImageOnKitKat(data));
							} else {
								//4.4之前图片解析
								onGetPictureListener.onComplete(handleImageBeforeKitKat(data));
							}

						}
					}
					break;

			}
		} else {// 如果用户打开之后没有选择图片就返回。则证明用户取消了选择。实现取消的接口
			if (null != onGetPictureListener)
			{
				onGetPictureListener.onCancel();
			}
			GetPictureFragment.this.dismiss();// 在该活动获得系统Activity返回的结果。处理玩再返回结果回到注册界面的时候记得把当前自己的弹出框关闭掉。
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

	/*申请权限的回调*/
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
			Logger.i(TAG, "onRequestPermissionsResult: permission granted");
			startCamera();


		} else {
			Logger.i(TAG, "onRequestPermissionsResult: permission denied");
			Toast.makeText(getContext(), "You Denied Permission", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 将拍的照片添加到相册
	 *
	 * @param uri 拍的照片的Uri
	 */
	private void galleryAddPic(Uri uri) {
		Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		mediaScanIntent.setData(uri);
		getContext().sendBroadcast(mediaScanIntent);
	}

	/**
	 * 4.4版本以上对返回的图片Uri的处理：
	 * 返回的Uri是经过封装的，要进行处理才能得到真实路径
	 *
	 * @param data 调用系统相册之后返回的Uri
	 */
	@TargetApi(19)
	private String handleImageOnKitKat(Intent data) {
		String imagePath = null;
		Uri uri = data.getData();
		if (DocumentsContract.isDocumentUri(getContext(), uri)) {
			//如果是document类型的Uri，则提供document id处理
			String docId = DocumentsContract.getDocumentId(uri);
			if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
				String id = docId.split(":")[1];//解析出数字格式的id
				String selection = MediaStore.Images.Media._ID + "=" + id;
				imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
			} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
				imagePath = getImagePath(contentUri, null);
			}
		} else if ("content".equalsIgnoreCase(uri.getScheme())) {
			//如果是content类型的uri，则进行普通处理
			imagePath = getImagePath(uri, null);
		} else if ("file".equalsIgnoreCase(uri.getScheme())) {
			//如果是file类型的uri，则直接获取路径
			imagePath = uri.getPath();
		}

		return imagePath;
	}

	/**
	 * 4.4版本以下对返回的图片Uri的处理：
	 * 就是从返回的Intent中取出图片Uri，直接显示就好
	 *
	 * @param data 调用系统相册之后返回的Uri
	 */
	private String handleImageBeforeKitKat(Intent data) {
		Uri uri = data.getData();
		String imagePath = getImagePath(uri, null);
		return imagePath;
	}

	/**
	 * 将Uri转化为路径
	 *
	 * @param uri       要转化的Uri
	 * @param selection 4.4之后需要解析Uri，因此需要该参数
	 * @return 转化之后的路径
	 */
	private String getImagePath(Uri uri, String selection) {
		String path = null;
		Cursor cursor = getContext().getContentResolver().query(uri, null, selection, null, null);
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
			}
			cursor.close();
		}
		return path;
	}

	/**
	 * 裁剪图片
	 * @param uri
	 */
	public void cropPhoto(Uri uri) {
		try {
			Intent intent = new Intent("com.android.camera.action.CROP");

			intent.setDataAndType(uri, "image/*");
			intent.putExtra(MediaStore.EXTRA_OUTPUT, mCropImageUriFromFile);
			intent.putExtra("crop", true);
			intent.putExtra("aspectX", outputX);
			intent.putExtra("aspectY", outputY);
			intent.putExtra("outputX", outputX);
			intent.putExtra("outputY", outputY);
			startActivityForResult(intent, CHOOSE_BIG_PICTURE);
		}catch (Exception mE){
			Toast.makeText(getActivity(),"Your device doesn't support the crop action!",Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * 头像选择接口的回调
	 */
	private OnGetPictureListener onGetPictureListener;

	public OnGetPictureListener getOnGetPictureListener() {
		return onGetPictureListener;
	}

	public void setOnGetPictureListener(OnGetPictureListener onGetPictureListener) {
		this.onGetPictureListener = onGetPictureListener;
	}

	/**
	 * 返回结果的监听器
	 *
	 * @author Whunf
	 *
	 */
	public interface OnGetPictureListener {
		/**
		 * 头像选择成功！
		 *
		 * @param result
		 */
		void onComplete(String result);

		/**
		 * 头像选择取消了。
		 */
		void onCancel();
	}
	/**
	 * 设置是否需要进行裁剪功能
	 */
	public void setIsNeed(boolean isNeed){
		this.isNeed = isNeed;
	}


}
